package cn.melonlib.reports.comp.web.ctrl;

import cn.melonlib.cores.commons.comp.web.ctrl.BasicController;
import cn.melonlib.cores.jpa.model.bean.collections.JsonMap;
import cn.melonlib.reports.comp.service.ModelDescriptionExportService;
import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/report/export")
public class ReportsExportCtrl extends BasicController {

    public void init(){
        System.out.println("initing...");
    }

    @Resource
    private ModelDescriptionExportService modelDescriptionExportService;

    @GetMapping("/schemas")
    @ResponseBody
    public void exportSchemasReport(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam("storeType") String storeType, @RequestParam("schemaName") String schemaName,
            @RequestParam("title") String title, @RequestParam("reportType") String reportType) throws Exception{
        System.out.println("running...");
        File file= modelDescriptionExportService.exportDataSchemas(storeType,schemaName,title,reportType, JsonMap.createMap());

        this.downloadConfig(request,response,title+"."+reportType,file.length(),switch (reportType){
            case "docx"-> "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            case "html"->"text/html;charset=utf-8";
            default -> "application/pdf";
        });
        try(InputStream in=new FileInputStream(file); OutputStream out=response.getOutputStream()){
            StreamUtils.copy(in,out);
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            FileUtils.deleteQuietly(file);
        }
    }
}
